﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using OutDbContext;
using Common.Logging;
using System.Web.Http.Controllers;
using User.Api.Dto.BirthCert;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class BirthCertController  : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(BirthCertController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 验证是否已经预约
        /// </summary>
        /// <param name="motherIdenNo">新生儿母亲身份证号</param>
        /// <returns>resultCode = 0 没有预约，1 信息已填写 2-已选时间 3-确定预约</returns>
        /// 
        [HttpGet]
        [ActionName("CheckApptInfo")]
        public BirthCertficateApptResponse CheckApptInfo(string motherIdenNo)
        {
            var apptInfo = new BirthCertificateApptInfo();
            
            //查询半年内的预约记录
            var lastDate = DateTime.Now.AddMonths(-6);
            apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.MotherIdenNo == motherIdenNo &&
               x.RecCreateDt >= lastDate && (x.RecStatus == 0 || x.RecStatus == 1 || x.RecStatus == 3));
            
            if (apptInfo == null)
            {
                return new BirthCertficateApptResponse
                {
                    ResultCode = "0",
                    ResultDesc = ""
                };
            }
            else
            {
                if (apptInfo.RecStatus == 0)
                {
                    return new BirthCertficateApptResponse
                    {
                        ResultCode = "1",
                        ResultDesc = "您已填写基本信息"
                    };
                }
                else if (apptInfo.RecStatus == 1)
                {
                    return new BirthCertficateApptResponse
                    {
                        ResultCode = "1",
                        ResultDesc = "您已选时间"
                    };
                }
                else
                {
                    return new BirthCertficateApptResponse
                    {
                        ResultCode = "3",
                        ResultDesc = "您预约成功"
                    };
                }
            }
        }

        /// <summary>
        /// 选择新生儿个数
        /// </summary>
        /// <param name="motherIdenNo"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("ChooseChildrenNum")]
        public ChooseChildrenNumResponse ChooseChildrenNum(string motherIdenNo)
        {
            return new ChooseChildrenNumResponse
            {
                MotherIdenNo = motherIdenNo
            };
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="motherIdenNo"></param>
        /// <param name="childrenNum"></param>
        /// <param name="apptInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("ParentInfo")]
        public ParentInfoResponse ParentInfo(string motherIdenNo, string childrenNum , string apptInfoId = "")
        {
            //Logger.ErrorFormat("motherIdenNo,信息：{0}", motherIdenNo);
            //Logger.ErrorFormat("childrenNum,信息：{0}", childrenNum);
            //Logger.ErrorFormat("apptInfoId,信息：{0}", apptInfoId);
            //var parentInfo = new ParentInfoResponse();
            //parentInfo.IsUpdateRec = apptInfoId != "";//是否修改信息
            //parentInfo.ApptInfoId = apptInfoId;
            if (string.IsNullOrEmpty(apptInfoId))
            {
                return new ParentInfoResponse
                {
                    MotherIdenNo = motherIdenNo,
                    ChildrenNum = childrenNum,
                    MotherName = "",
                    MotherPhone = "",
                    FatherPhone = ""
                };
            }
            else //如果修改信息，查询数据库记录
            {
                var apptId = apptInfoId.ToInt32OrDefault();
                var apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.Id == apptId);
                if (apptInfo == null)
                {
                    return new ParentInfoResponse
                    {
                        IsGetApptInfoSucceed = false,
                        ErrMsg = "没有找到您的预约信息"
                    };
                }
                return new ParentInfoResponse
                {
                    MotherIdenNo = apptInfo.MotherIdenNo,
                    ChildrenNum = apptInfo.ChildrenNum.ToString(),
                    MotherName = apptInfo.MotherName,
                    MotherPhone = apptInfo.MotherPhone,
                    FatherPhone = apptInfo.FatherPhone
                };
            }
        }
        /// <summary>
        /// 新生儿信息
        /// </summary>
        /// <param name="motherIdenNo"></param>
        /// <param name="childrenNum"></param>
        /// <param name="motherName"></param>
        /// <param name="motherPhone"></param>
        /// <param name="fatherPhone"></param>
        /// <param name="apptInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("ChildrenInfo")]
        public ChildrenInfoResponse ChildrenInfo(string motherIdenNo, string childrenNum, string motherName,
            string motherPhone, string fatherPhone, string apptInfoId = "")
        {
            //Logger.ErrorFormat("childrenNum11,信息：{0}", childrenNum);
            //Logger.ErrorFormat("motherName22,信息：{0}", motherName);
            
            //var parentInfo = new ChildrenInfoResponse();
            //parentInfo.IsUpdateRec = apptInfoId != "0";
            if (string.IsNullOrEmpty(apptInfoId))
            {
                return new ChildrenInfoResponse
                {
                    ChildrenNum= childrenNum,
                    IsGetApptInfoSucceed = true,
                    FirstBabyName = "",
                    FirstBabySex = "",
                    FirstBabyBirthdate = "",
                    SecondBabyName = "",
                    SecondBabySex = "",
                    // SecondBabyBirthdate = apptInfo.SecondBabyBirthdate,
                    ThirdBabyName = "",
                    ThirdBabySex = "",
                    //ThirdBabyBirthdate = apptInfo.ThirdBabyBirthdate
                };
            }
            else //如果修改信息，查询数据库记录
            {
                var apptId = apptInfoId.ToInt32OrDefault();
                var apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.Id == apptId);
                if (apptInfo == null)
                {
                    return new ChildrenInfoResponse
                    {
                        IsGetApptInfoSucceed = false,
                        ErrMsg = "没有找到您的预约信息"
                    };
                }
                return new ChildrenInfoResponse
                {
                    IsGetApptInfoSucceed = true,
                    ApptInfoId = apptInfoId,
                    ChildrenNum = childrenNum,
                    FirstBabyName = apptInfo.FirstBabyName,
                    FirstBabySex = apptInfo.FirstBabyGender,
                    FirstBabyBirthdate = apptInfo.FirstBabyBirthdate,
                    SecondBabyName = apptInfo.SecondBabyName,
                    SecondBabySex = apptInfo.SecondBabyGender,
                   // SecondBabyBirthdate = apptInfo.SecondBabyBirthdate,
                    ThirdBabyName = apptInfo.ThirdBabyName,
                    ThirdBabySex = apptInfo.ThirdBabyGender,
                    //ThirdBabyBirthdate = apptInfo.ThirdBabyBirthdate
                };
            }
        }

        /// <summary>
        /// 选取预约时段
        /// </summary>
        /// <param name="motherIdenNo"></param>
        /// <param name="motherName"></param>
        /// <param name="motherPhone"></param>
        /// <param name="fatherPhone"></param>
        /// <param name="childrenNum"></param>
        /// <param name="firstBabyName"></param>
        /// <param name="firstBabySex"></param>
        /// <param name="firstBabyBirthDate"></param>
        /// <param name="secondBabyName"></param>
        /// <param name="secondBabySex"></param>
        /// <param name="secondBabyBirthDate"></param>
        /// <param name="thirdBabyName"></param>
        /// <param name="thirdBabySex"></param>
        /// <param name="thirdBabyBirthDate"></param>
        /// <param name="apptInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SelectApptTime")]
        public SelectApptTimeResponse SelectApptTime(string motherIdenNo, string motherName, string motherPhone, string fatherPhone,
            string childrenNum, string firstBabyName, string firstBabySex, string firstBabyBirthDate,
             string secondBabyName = "", string secondBabySex = "", 
                string thirdBabyName = "", string thirdBabySex = "", string apptInfoId = "")
        {
            //Logger.ErrorFormat("apptInfoId,信息：{0}", apptInfoId);
           
            var azUser = AzUser.GetInApi(Request);
            var viewModel = new SelectApptTimeResponse();
            
            var apptInfo = new BirthCertificateApptInfo();
            if (string.IsNullOrEmpty(apptInfoId))
            {
                var lastDate = DateTime.Now.AddMonths(-6);
                apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.MotherIdenNo == motherIdenNo && (x.RecStatus == 0 || x.RecStatus == 1)
                            && x.RecCreateDt >= lastDate);
                if (apptInfo == null)
                {
                    apptInfo = new BirthCertificateApptInfo();
                    apptInfo.WxUserId = azUser.UserId;
                    apptInfo.MotherIdenNo = motherIdenNo;
                    apptInfo.ChildrenNum = childrenNum.ToInt32();
                    apptInfo.MotherName = motherName;
                    apptInfo.MotherPhone = motherPhone;
                    apptInfo.FatherPhone = fatherPhone;
                    apptInfo.FirstBabyName = firstBabyName;
                    apptInfo.FirstBabyGender = firstBabySex;
                    apptInfo.FirstBabyBirthdate = firstBabyBirthDate;
                    apptInfo.RecCreateDt = System.DateTime.Now;
                    apptInfo.RecUpdateDt = System.DateTime.Now;
                    apptInfo.RecStatus = 0; //填写信息完成 

                    if (childrenNum.ToInt32() > 1) //2孩
                    {
                        apptInfo.SecondBabyName = secondBabyName;
                        apptInfo.SecondBabyGender = secondBabySex;
                        //apptInfo.SecondBabyBirthdate = secondBabyBirthDate;
                    }
                    if (childrenNum.ToInt32() > 2) //3孩
                    {
                        apptInfo.ThirdBabyName = thirdBabyName;
                        apptInfo.ThirdBabyGender = thirdBabySex;
                        //apptInfo.ThirdBabyBirthdate = thirdBabyBirthDate;
                    }
                    _ctx.BirthCertificateApptInfo.Add(apptInfo);
                }
                else
                {
                    apptInfo.WxUserId = azUser.UserId;
                    apptInfo.RecStatus = 0;
                    apptInfo.RecUpdateDt = System.DateTime.Now;
                }
            }
            else
            {
                var apptId = apptInfoId.ToInt32OrDefault();
                apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.Id == apptId);
                if (apptInfo == null)
                {
                    return new SelectApptTimeResponse
                    {
                        IsGetApptTimeSucceed = false,
                        ErrMsg = "没有查询到您的预约信息"
                    };
                }
                apptInfo.WxUserId = azUser.UserId;
                apptInfo.MotherName = motherName;
                apptInfo.MotherPhone = motherPhone;
                apptInfo.FatherPhone = fatherPhone;
                apptInfo.FirstBabyBirthdate = firstBabyBirthDate;
                apptInfo.FirstBabyGender = firstBabySex;
                apptInfo.FirstBabyName = firstBabyName;
                apptInfo.RecStatus = 0;  //信息已登记

                if (apptInfo.ChildrenNum > 1) //2孩
                {
                    apptInfo.SecondBabyName = secondBabyName;
                    apptInfo.SecondBabyGender = secondBabySex;
                }
                if (apptInfo.ChildrenNum > 2) //3孩
                {
                    apptInfo.ThirdBabyName = thirdBabyName;
                    apptInfo.ThirdBabyGender = thirdBabySex;
                }
            }
            _ctx.SaveChanges();

            var apptConfig = new BirthCertApptConfig();

            var apptWeeks = 1;
            var apptWeekdays = "2,4";
            var apptTimeSlice = "14:30-16:30";
            var maxCount = 40;
            var apptStartDate = 6; //预约开始日期，在当天日期多少天后
            var notApptDateList = new List<BirthCertNotApptDate>();
            try
            {
                apptConfig = _ctx.BirthCertApptConfig.FirstOrDefault();
                if (apptConfig != null)
                {
                    apptWeeks = apptConfig.ApptWeek;
                    apptWeekdays = apptConfig.ApptWeekday;
                    apptTimeSlice = apptConfig.ApptStartTime + "-" + apptConfig.ApptEndTime;
                    maxCount = apptConfig.MaxCount;
                    apptStartDate = apptConfig.ApptStartDate; //预约开始日期，在当天日期多少天后
                }
                var dtNow = System.DateTime.Now.Date;
                notApptDateList = _ctx.BirthCertNotApptDate.Where(x => x.RecStatus == 1 && x.Date > dtNow).ToList();
            }
            catch
            { }

            var dateList = new List<DateTime>();
            var weekdays = apptWeekdays.Split(",");
            var dateNow = DateTime.Now.Date;
            for (int i = apptStartDate; i < apptStartDate + 7 * apptWeeks; i++)
            {
                dateNow = DateTime.Now.Date.AddDays(i);
                if (weekdays.Contains(dateNow.DayOfWeek.ToInt32OrDefault().ToString()))
                {
                    dateList.Add(dateNow);
                }
            }
            if (dateList.Count == 0) //日期
            {
                return new SelectApptTimeResponse
                {
                    IsGetApptTimeSucceed = false,
                    ErrMsg = "没有查询到您的预约信息"
                };
            }

            viewModel.SourceList= new List<SelectApptTimeResponse.ApptSource>();
            string strDate = "";
            SelectApptTimeResponse.ApptSource source;

            #region no apptdate 
            var notApptDates = new List<DateTime>();
            if (notApptDateList != null)
            {
                foreach (var notApptDate in notApptDateList)
                {
                    notApptDates.Add(notApptDate.Date);
                }
            }
            #endregion
            foreach (var date in dateList)
            {
                if (notApptDates.Contains(date))
                {
                    continue;
                }
                strDate = date.ToString("yyyy-MM-dd");

                var apptInfos = _ctx.BirthCertificateApptInfo.Where(x => x.ToFetchDate == strDate &&
                    x.RecStatus == 3).Take(maxCount).ToList(); //预约成功

                source = new SelectApptTimeResponse.ApptSource();
                source.ApptDate= date.ToString("yyyy-MM-dd");
                source.TimeSlice = apptTimeSlice;
                source.LeaveCount = maxCount;
                if (apptInfos != null && apptInfos.Count() > 0)
                    source.LeaveCount = maxCount - apptInfos.Count();
                source.WeekDay = GetChineseWeek(date.DayOfWeek.ToString());
                viewModel.SourceList.Add(source);
            }

            if (viewModel.SourceList.Count == 0)
            {
                return new SelectApptTimeResponse
                {
                    IsGetApptTimeSucceed = false,
                    ErrMsg = "没有查询到您的预约信息"
                };
            }
            return new SelectApptTimeResponse
            {
                SourceList=viewModel.SourceList,
                ApptInfoId= apptInfo.Id.ToString()
            };
        }
        /// <summary>
        /// 预约确定
        /// </summary>
        /// <param name="apptInfoId"></param>
        /// <param name="toFetchDate"></param>
        /// <param name="timeSlice"></param>
        /// <param name="motherIdenNo"></param>
        /// <param name="updateRec"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("ApptInfoConfirm")]
        public ApptInfoConfirmResponse ApptInfoConfirm(string apptInfoId, string toFetchDate, string timeSlice)
        {
            //Logger.ErrorFormat("apptInfoId,信息：{0}", apptInfoId);
            //var validateFetchDate = false; //领取日期
            //var noEnoughSource = false; //没有足够号源
            //var maxCount = 40; //最多号源数
            var apptInfo = new BirthCertificateApptInfo();
            var apptId = apptInfoId.ToInt32OrDefault();
            apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.Id == apptId);
            if (apptInfo != null)
            {
                apptInfo.ToFetchDate = toFetchDate;
                apptInfo.TimeSlice = timeSlice;
                apptInfo.ApptTime = System.DateTime.Now;
                apptInfo.RecUpdateDt = System.DateTime.Now;
                apptInfo.RecStatus = 1;
                //apptInfo.ApptNo = AppointService.GetBirthCertApptNo(toFetchDate);
            }
            _ctx.SaveChanges();

            if (apptInfo == null)
            {
                return new ApptInfoConfirmResponse
                {
                    IsGetApptInfoSucceed = false,
                    ErrMsg = "没有查询到你登记的信息"
                };
            }
            var news = _ctx.BirthCertificateApptInfo.Where(x => x.Id == apptId).ToList();
            return new ApptInfoConfirmResponse
            {
                IsGetApptInfoSucceed = true,
                ApptInfoList = news.Select(x => new ApptInfoConfirmResponse.ApptInfoConfirmList
                {
                   ToFetchDate = x.ToFetchDate,
                   TimeSlice = x.TimeSlice,
                   ApptNo = x.ApptNo,
                   ApptTime = x.ApptTime,
                   MotherName =x.MotherName,
                   MotherIdenNo=x.MotherIdenNo,
                   MotherPhone=x.MotherPhone,
                   FatherPhone = x.FatherPhone,
                   ChildrenNum=x.ChildrenNum,
                   FirstBabyName=x.FirstBabyName,
                   FirstBabyGender=x.FirstBabyGender,
                   FirstBabyBirthdate=x.FirstBabyBirthdate,
                   SecondBabyName=x.SecondBabyName,
                   SecondBabyGender=x.SecondBabyGender,
                   ThirdBabyName=x.ThirdBabyName,
                   ThirdBabyGender=x.ThirdBabyGender
                }).ToList()
            };
        }
        /// <summary>
        /// 预约详情
        /// </summary>
        /// <param name="apptInfoId"></param>
        /// <param name="motherIdenNo"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        [ActionName("ApptInfoDetail")]
        public ApptInfoDetailResponse ApptInfoDetail(string apptInfoId, string motherIdenNo = "")
        {
            //Logger.ErrorFormat("apptInfoId,信息：{0}", apptInfoId);
            //Logger.ErrorFormat("motherIdenNo,信息：{0}", motherIdenNo);
            var apptInfo = new BirthCertificateApptInfo();
            var apptId = apptInfoId.ToInt32OrDefault();
            var lastDate = DateTime.Now.AddMonths(-6); 
            if (string.IsNullOrEmpty(motherIdenNo) && !string.IsNullOrEmpty(apptInfoId)) //非查询页面跳转
            {
                apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.Id == apptId);
                if (apptInfo != null)
                {
                    apptInfo.ApptTime = System.DateTime.Now;
                    apptInfo.RecUpdateDt = System.DateTime.Now;
                    apptInfo.RecStatus = 3;
                }
                _ctx.SaveChanges();
            }
            else
            {
                apptInfo = _ctx.BirthCertificateApptInfo.FirstOrDefault(x => x.MotherIdenNo == motherIdenNo &&
                    x.ApptTime > lastDate);
                if (apptInfo != null)
                {
                    apptInfo.ApptTime = System.DateTime.Now;
                    apptInfo.RecUpdateDt = System.DateTime.Now;
                    apptInfo.RecStatus = 3;
                }
                _ctx.SaveChanges();
            }
            if (apptInfo == null)
            {
                return new ApptInfoDetailResponse
                {
                    IsGetApptInfoSucceed = false,
                    ErrMsg = "没有查询到您登记的信息"
                };
            }
            var apptTimeDate = apptInfo.ApptTime.Value.ToString("yyyy-MM-dd");
            var nowDate = System.DateTime.Now.ToString("yyyy-MM-dd");
            var news = _ctx.BirthCertificateApptInfo.Where(x => x.Id == apptId ||x.MotherIdenNo == motherIdenNo && x.ApptTime > lastDate).ToList();
            var isCouldModify = false;
            if (apptInfo.ApptTime == null)
            {
                isCouldModify = true;
            }
            if (apptInfo.ApptTime.HasValue)
            {
                if (nowDate == apptTimeDate)
                {
                    isCouldModify = true;
                }
            }
            return new ApptInfoDetailResponse
            {
                IsCouldModify = isCouldModify,
                IsGetApptInfoSucceed = true,
                ApptInfoList = news.Select(x => new ApptInfoDetailResponse.ApptInfoDetailList
                {
                    Id=x.Id,
                    MotherName = x.MotherName,
                    MotherIdenNo = x.MotherIdenNo,
                    MotherPhone = x.MotherPhone,
                    FatherPhone = x.FatherPhone,
                    ToFetchDate = x.ToFetchDate,
                    ApptTime = x.ApptTime.ToString(),
                    ApptNo = x.ApptNo,
                    TimeSlice = x.TimeSlice,
                    ChildrenNum = x.ChildrenNum,
                    FirstBabyName = x.FirstBabyName,
                    FirstBabyGender = x.FirstBabyGender,
                    FirstBabyBirthdate = x.FirstBabyBirthdate,
                    SecondBabyName = x.SecondBabyName,
                    SecondBabyGender = x.SecondBabyGender,
                    ThirdBabyName = x.ThirdBabyName,
                    ThirdBabyGender = x.ThirdBabyGender
                }).ToList()
            };
        }

        /// <summary>
        /// 我要报名
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("HospCurriculum")]
        public HospCurriculumResponse HospCurriculum()
        {
            var azUser = AzUser.GetInApi(Request);
            var user = _ctx.WxUser.FirstOrDefault(x => x.RecStatus == 1 && x.Id == azUser.UserId);

            if (user != null)
            {
                var hosp = _ctx.HospCurriculum.FirstOrDefault(x => x.RecStatus == 1 && x.OpenId == user.OpenId);
                if (hosp != null)
                {
                    return new HospCurriculumResponse
                    {
                        ErrMsg="你已经报名成功"
                    };
                }

                var model = new HospCurriculum
                {
                    OpenId = user.OpenId,
                    WxUserId = user.Id,
                    RecStatus = 1,
                    RecCreateDt = DateTime.Now,
                };
                _ctx.HospCurriculum.Add(model);
            }
            return new HospCurriculumResponse
            {
                ErrMsg = "报名成功"
            };
        }

        public static string GetChineseWeek(string englishWeek)
        {
            var chineseWeek = "";
            switch (englishWeek)
            {
                case "Monday":
                    chineseWeek = "星期一";
                    break;
                case "Tuesday":
                    chineseWeek = "星期二";
                    break;
                case "Wednesday":
                    chineseWeek = "星期三";
                    break;
                case "Thursday":
                    chineseWeek = "星期四";
                    break;
                case "Friday":
                    chineseWeek = "星期五";
                    break;
                case "Saturday":
                    chineseWeek = "星期六";
                    break;
                case "Sunday":
                    chineseWeek = "星期天";
                    break;
                default:
                    break;
            }
            return chineseWeek;
        }

    }
}